package cn.tedu.travelsystem.itineraryDetail.controller;

import cn.tedu.travelsystem.base.response.JsonResult;
import cn.tedu.travelsystem.base.response.StatusCode;
import cn.tedu.travelsystem.itineraryDetail.mapper.ItineraryDetailMapper;
import cn.tedu.travelsystem.itineraryDetail.pojo.dto.ItineraryDetailDTO;
import cn.tedu.travelsystem.itineraryDetail.pojo.entity.ItineraryDetail;
import cn.tedu.travelsystem.itineraryDetail.pojo.vo.ItineraryDetailVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/itinerary-details")
@Api(tags = "08.行程详情模块")
public class ItineraryDetailController {

    @Autowired
    private ItineraryDetailMapper itineraryDetailMapper;


    @PostMapping("/batch-insert")
    public JsonResult batchAddItineraryDetails(@Validated @RequestBody List<ItineraryDetailDTO> dtos) {
        log.debug("Received batch insert request with data: {}", dtos);
        List<ItineraryDetail> details = dtos.stream().map(dto -> {
            ItineraryDetail detail = new ItineraryDetail();
            BeanUtils.copyProperties(dto, detail);
            return detail;
        }).collect(Collectors.toList());

        try {
            int rows = itineraryDetailMapper.batchInsert(details);
            return rows > 0 ? JsonResult.ok() : new JsonResult(StatusCode.SAVE_FAILED);
        } catch (Exception e) {
            log.error("批量插入失败", e);
            return new JsonResult(StatusCode.SAVE_FAILED);
        }
    }

    @PostMapping("/insert")
    @ApiOperation("添加行程详情信息")
    @ApiOperationSupport(order = 10)
    public JsonResult addItineraryDetail(@Validated @RequestBody ItineraryDetailDTO dto) {
        log.debug("ItineraryDetailDTO = " + dto);
        ItineraryDetail itineraryDetail = new ItineraryDetail();
        BeanUtils.copyProperties(dto, itineraryDetail);
        // 补充必要字段的默认值
        if (itineraryDetail.getStatus() == null) {
            itineraryDetail.setStatus(1); // 默认状态为待确认
        }
        int rows = itineraryDetailMapper.insert(itineraryDetail);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @DeleteMapping("/{detailId}")
    @ApiOperation("删除行程详情信息")
    @ApiOperationSupport(order = 20)
    public JsonResult deleteItineraryDetail(@PathVariable Integer detailId) {
        log.debug("detailId = " + detailId);
        int rows = itineraryDetailMapper.deleteById(detailId);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @PutMapping("/{detailId}")
    @ApiOperation("更新行程详情信息")
    @ApiOperationSupport(order = 30)
    public JsonResult updateItineraryDetail(@PathVariable Integer detailId, @Validated @RequestBody ItineraryDetailDTO dto) {
        log.debug("detailId = " + detailId + ", ItineraryDetailDTO = " + dto);
        ItineraryDetail itineraryDetail = new ItineraryDetail();
        BeanUtils.copyProperties(dto, itineraryDetail);
        itineraryDetail.setDetail_id(detailId);
        int rows = itineraryDetailMapper.update(itineraryDetail);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @GetMapping("/{detailId}")
    @ApiOperation("查询单个行程详情信息")
    @ApiOperationSupport(order = 40)
    public JsonResult getItineraryDetail(@PathVariable Integer detailId) {
        log.debug("detailId = " + detailId);
        ItineraryDetail itineraryDetail = itineraryDetailMapper.selectById(detailId);
        if (itineraryDetail != null) {
            ItineraryDetailVO vo = new ItineraryDetailVO();
            BeanUtils.copyProperties(itineraryDetail, vo);
            return JsonResult.ok(vo);
        } else {
            return new JsonResult(StatusCode.DATA_NOT_FOUND);
        }
    }

    @GetMapping
    @ApiOperation("查询所有行程详情信息")
    @ApiOperationSupport(order = 50)
    public JsonResult getAllItineraryDetails() {
        log.debug("查询所有行程详情信息");
        List<ItineraryDetail> itineraryDetails = itineraryDetailMapper.selectAll();
        List<ItineraryDetailVO> vos = new ArrayList<>();
        for (ItineraryDetail itineraryDetail : itineraryDetails) {
            ItineraryDetailVO vo = new ItineraryDetailVO();
            BeanUtils.copyProperties(itineraryDetail, vo);
            vos.add(vo);
        }
        return JsonResult.ok(vos);
    }

    @GetMapping("/user")
    @ApiOperation("根据用户ID查询行程详情")
    public JsonResult getByUserId(@RequestParam("user_id") Integer userId) {
        List<ItineraryDetail> details = itineraryDetailMapper.selectByUserId(userId);
        List<ItineraryDetailVO> vos = new ArrayList<>();
        for (ItineraryDetail detail : details) {
            ItineraryDetailVO vo = new ItineraryDetailVO();
            BeanUtils.copyProperties(detail, vo);
            vos.add(vo);
        }
        return JsonResult.ok(vos);
    }

    @GetMapping("/user/page")
    @ApiOperation("分页查询用户行程")
    public JsonResult getByUserIdPage(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        PageHelper.startPage(page, pageSize);
        List<ItineraryDetail> details = itineraryDetailMapper.selectByUserId(userId);
        PageInfo<ItineraryDetail> pageInfo = new PageInfo<>(details);

        List<ItineraryDetailVO> vos = details.stream().map(detail -> {
            ItineraryDetailVO vo = new ItineraryDetailVO();
            BeanUtils.copyProperties(detail, vo);
            return vo;
        }).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", vos);
        result.put("total", pageInfo.getTotal());
        return JsonResult.ok(result);

    }
}